package com.west_traveler.play_service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class PlayService extends Service {

    private MediaPlayer player;
    private LocalBroadcastManager manager;
    private Intent receiverIntent;
    private String[] playUrlArrays;
    private int index;
    private Timer timer;


    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        manager = LocalBroadcastManager.getInstance(getApplicationContext());

        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                player.start();

                sendTotalProgress();

                playerOptions();

                receiverIntent.putExtra("isPlaying", player.isPlaying());
                manager.sendBroadcast(receiverIntent);

                player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
                    @Override
                    public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {

                        receiverIntent.putExtra("bufferProgress", i);
                        manager.sendBroadcast(receiverIntent);

                    }
                });
            }
        });

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                receiverIntent.putExtra("isCompletion", true);
                manager.sendBroadcast(receiverIntent);
            }
        });

    }

    private void sendTotalProgress() {
        receiverIntent = new Intent();
        receiverIntent.setAction("ximalaya.fm.progress");
        receiverIntent.addCategory(Intent.CATEGORY_DEFAULT);
        receiverIntent.putExtra("totalProgress", player.getDuration());
        manager.sendBroadcast(receiverIntent);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    public void play() {

        if (player.isPlaying()) {
            player.pause();
        } else {
            player.start();
        }

        playerOptions();

        receiverIntent.putExtra("isPlaying", player.isPlaying());
        manager.sendBroadcast(receiverIntent);
    }

    public void setCurrentTime(int seekToTime) {
        player.seekTo(seekToTime);
        player.start();

        receiverIntent.putExtra("isPlaying", player.isPlaying());
        manager.sendBroadcast(receiverIntent);

        playerOptions();
    }

    public void previous() {
        int curIndex = --index;
        if (curIndex >= 0) {

            try {
                player.reset();
                player.setDataSource(playUrlArrays[curIndex]);
                player.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void next() {
        int curIndex = ++index;
        if(curIndex<playUrlArrays.length){
            try {
                player.reset();
                player.setDataSource(playUrlArrays[curIndex]);
                player.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    public class PlayBinder extends Binder {
        public PlayService getService() {
            return PlayService.this;
        }
    }


    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        if (intent != null) {
            player.reset();
            playUrlArrays = intent.getStringArrayExtra("playUrlArrays");
            index = intent.getIntExtra("index", -1);

            new Thread() {
                @Override
                public void run() {


                    try {

                        player.setDataSource(playUrlArrays[index]);
                        player.prepare();


                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }
            }.start();

        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void playerOptions() {
        if (timer != null) {
            timer.cancel();
        }

        if (player.isPlaying()) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    receiverIntent.putExtra("currentProgress", player.getCurrentPosition());
                    manager.sendBroadcast(receiverIntent);
                }
            }, 0, 1000);

        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player != null) {
//            player.stop();
            player.release();
            player = null;
        }

        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }


}
